package com.example.aline.kotlindemo.utils

import com.example.aline.kotlindemo.BaseActivity

/**
 * Created by liguoying on 2017/10/18.
 * activity 管理类 单例
 */
object ActivitiesManager {

    fun getInstance(): ActivitiesManager {
        return this
    }

    private val activities = arrayListOf<BaseActivity>()

    fun addActivity(activity: BaseActivity) {
        activities.add(activity)
    }

    fun currentActivity(): BaseActivity? {
        return if (activities.isEmpty()) null else activities[activities.lastIndex]
    }

    fun findActivity(clazz: Class<*>): BaseActivity? {
        var activity: BaseActivity? = null
        findIt@ for (aty in activities) {
            if (aty.javaClass == clazz) {
                activity = aty
                break@findIt
            }
        }
        return activity
    }

    fun removeActivity(activity: BaseActivity) {
        activities.remove(activity)
    }

    private fun finishActivity(activity: BaseActivity?) {
        if (activity != null) {
            activities.remove(activity)
            activity.finish()
        }
    }

    fun finishActivity(clazz: Class<*>) {
        for (activity in activities) {
            if (activity.javaClass == clazz) {
                finishActivity(activity)
            }
        }
    }

    //    vararg 可变参数的声明类型
    fun finishAllActivitiesExcept(vararg clazz: Class<*>) {
        for (i in activities.lastIndex downTo 0) {
            var shouldFinish = true
            clazz.forEach {
                if (activities[i].javaClass == it) {
                    shouldFinish = false
                    return@forEach
                }
            }
            if (shouldFinish) {
                finishActivity(activities[i])
            }
        }
    }

    fun finishAllActivities() {
        activities.forEach {
            if (!it.isFinishing) {
                it.finish()
            }
        }
        activities.clear()
    }
}